<?php


namespace app\api\controller\v22;


use app\api\controller\v2\Auth;
use app\common\cachemodel\NatalGoods;
use app\common\cachemodel\SystemConfig;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\ZlSynastryReport;
use app\common\lib\ConfigManage;
use app\common\lib\Natal;
use app\common\lib\Util;
use app\common\model\Recode;
use Exception;
use think\Env;

/**
 * @version 2.5.1
 * 本命报告和视频详情
 * Class NatalReport
 * @package app\api\controller\v22
 */
class NatalReport extends Auth
{
    /**
     * 本命预测
     * @throws Exception
     */
    public function index()
    {
        $rid = input('rid/d', 0);
        $uid = $this->user['id'];

        $recodeModel = new Recode();
        $NatalReportModel = new \app\common\cachemodel\NatalReport();
        if ($rid)
        {
            $recodeInfo = $recodeModel->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
            if (!$recodeInfo)
            {
                return show(config('code.error'), '档案不存在');
            }
        } else
        {
            $recodeInfo = $recodeModel->getSelfRecode(['uid' => $this->user['id']]);
            if (!$recodeInfo)
            {
                return show(config('code.error'), '档案不存在');
            }
            $rid = $recodeInfo['id'];
        }
        //  获取系统配置
        $config = (new SystemConfig())->getSystemConfig(['title1', 'title_intro1', 'title2', 'title_intro2']);
        //  获取分数及词条
        $natal = (new Natal())->getScoreAndText($recodeInfo);
        //  获取本命预测商品信息
        $goodData = (new NatalGoods())->getGoods();
        // 获取合盘报告商品
        if (Util::getSynastryReportSwitch() && Util::CheckAppVersion('2.5.2') !== '小')
        {
            $synastryReportGoods = (new \app\common\cachemodel\Goods())->GoodsTypeInfo(17);
            $goodData = array_merge($synastryReportGoods, $goodData);
        }
        // 获取解锁订单信息状态
        $unlockReport = $NatalReportModel->getNatalReport2($recodeInfo);
        // $unlockReport = $NatalReportModel->getNatalReport($uid, $rid);

        $forecast = [];//报告数据
        //长图排序
        $large_unlocking = [];
        $large_active = [];
        $large_unopen = [];
        $large_lock = [];
        $large_unlock = [];
        //短图排序
        $small_unlocking = [];
        $small_active = [];
        $small_unopen = [];
        $small_lock = [];
        $small_unlock = [];
        $bar_sort_index = [];//柱状图排序
        $orderModel = new \app\common\cachemodel\Orders();
        $activingModel = new ZhunleActivity();
        $oldNatalScore = ['feelings' => 'love', 'dating' => 'home', 'carrer' => 'work', 'money' => 'money', 'academic' => 'study'];
        //获取报告商品图片
        $reportImage = ConfigManage::natalReportGoodImage(1);
        foreach (array_values($goodData) as $key => $item)
        {
            $goodType = (isset($item['good_type']) && $item['good_type'] === 17) ? 17 : 7;
            if ((int)$item['status'] === 2)//暂不开放状态
            {
                $status = 3;
            } else//判断商品解锁状态
            {
                if ($goodType === 17)
                {   // 合盘报告
                    // 检测 是否购买过
                    $unlockStatus = (new ZlSynastryReport())->getUserHasReportUnlockStatus($this->user['id'], $rid, 0, $item['srid']);
                    $status = $unlockStatus ? 2 : 0;
                } else
                {   // 本命报告
                    if (isset($unlockReport[$item['id']]))
                    {
                        $unlock_status = (int)$unlockReport[$item['id']]['status'] === 2 ? 2 : 1;
                        $status = isset($unlockReport[$item['id']]) ? ($unlock_status) : 0;
                    } else
                    {
                        $status = 0;
                    }
                }
            }

            $is_large = 0;

            if ($goodType === 17)
            {  // 合盘报告
                $is_large = $item['is_large'] ? 1 : 0;
                $bg_img = $item['is_large'] ? $item['bg_img'] : $item['small_bg_img'];
            } else
            {   // 本命报告
                //获取活动商品信息
                $activing = $activingModel->getActivingGood($goodType, $item['id']);
                $actiGids = $activing ? explode(',', $activing['gids']) : [];

                //判断当前图是否为长图
                if (in_array($item['flag'], $reportImage['large_goods'], true))
                {
                    $is_large = 1;
                    $bg_img = $reportImage['large'][$item['flag']];
                } else
                {
                    $bg_img = $reportImage['small'][$item['flag']];
                }

                if (in_array($item['id'], $actiGids, false))
                {
                    $bg_img = $is_large === 1 ? $reportImage['large_active'][$item['flag']] : $reportImage['small_active'][$item['flag']];
                }
            }

            if ($goodType === 17)
            {
                $d = [
                    'score' => $item['score'] ?? 0,
                    'text' => $item['score'] ?? '',
                    'status' => $status,
                    'alert_bg_img1' => $item['alert_bg_img1'] ?? '',
                    'alert_bg_img2' => $item['alert_bg_img2'] ?? '',
                    'bg_img' => $bg_img,
                    'title_img' => $item['title_img'] ?? '',
                    'unlock_num' => $item['base_num'] + $orderModel->getTotalPrepaidOrder($goodType, $item['srid']),
                    'intro' => $item['intro'] ?? '',
                    'gcolor' => $item['color'] ?? '',
                    'gname' => $item['name'] ?? '',
                    'active_time' => 0,
                    'target' => 'local',
                    'link' => $status === 0 ?
                        "synastry_report_detail?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=1" :    // 下单介绍页
                        "synastry_report_list?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=1"  // 查看合盘报告列表
                ];
            } else
            {
                $d = [
                    // 'gid' => (int)$item['id'],
                    'score' => $natal[$oldNatalScore[$item['flag']]] ?? 0,
                    'text' => $natal[$oldNatalScore[$item['flag']] . '_text'] ?? '',
                    'status' => $status,
                    'alert_bg_img1' => $item['alert_bg_img1'] ?? '',
                    'alert_bg_img2' => $item['alert_bg_img2'] ?? '',
                    'bg_img' => $bg_img,
                    'title_img' => $item['title_img'] ?? '',
                    'unlock_num' => $item['base_num'] + $orderModel->getTotalPrepaidOrder($goodType, $item['id']),
                    'intro' => $item['intro'] ?? '',
                    'gcolor' => $item['color'] ?? '',
                    'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
//                'active_time' => $item['active_time']
                    'active_time' => 0,
                    'target' => 'local',
                    'link' => "report_details?rid={$rid}&gid={$item['id']}&need_auth=1"
                ];
            }

            //长图
            if ($is_large)
            {
                if ($status === 1)
                {   // 解锁中
                    $large_unlocking[] = $key;
                } elseif ($status === 0 && $d['active_time'] > 0)
                {   // 限时特价 并且 未解锁
                    $large_active[] = $key;
                } elseif (!$status)
                {   // 未解锁
                    $large_lock[] = $key;
                } elseif ($status === 3)
                {
                    //未开放
                    $large_unopen[] = $key;
                } else
                {   // 已解锁
                    $large_unlock[] = $key;
                }
            } //短图
            else
            {
                if ($status === 1)
                {   // 解锁中
                    $small_unlocking[] = $key;
                } elseif ($status === 0 && $d['active_time'] > 0)
                {   // 限时特价 并且 未解锁
                    $small_active[] = $key;
                } elseif (!$status)
                {   // 未解锁
                    $small_lock[] = $key;
                } elseif ($status === 3)
                {
                    //未开放
                    $small_unopen[] = $key;
                } else
                {   // 已解锁
                    $small_unlock[] = $key;
                }
            }
            //柱状图
            if ($goodType !== 17)
            {
                $bar_sort_index[] = $key;
            }
            //报告数据
            $forecast[] = $d;
        }

        $pageTitle = '一生报告';
        if (Util::CheckAppVersion('2.10.0') !== '小')
        {
            $pageTitle = '深度解读';
            $config['title2'] = '深度解读';
        }

        $data = [
            'page_title' => Util::IsHuaweiAndOppo() ? '节律报告' : $pageTitle,
            'title1' => Util::IsHuaweiAndOppo() ? '格局分数' : ((isset($config['title1']) && !empty($config['title1'])) ? $config['title1'] : ''),
            'title_intro1' => (isset($config['title_intro1']) && !empty($config['title_intro1'])) ? $config['title_intro1'] : '',
            'title2' => Util::IsHuaweiAndOppo() ? '节律报告' : ((isset($config['title2']) && !empty($config['title2'])) ? $config['title2'] : ''),
            'title_intro2' => (isset($config['title_intro2']) && !empty($config['title_intro2'])) ? $config['title_intro2'] : '',
            'forecast_list' => $forecast,
            // 'large_sort_index' => array_merge($large_unlocking, $large_unlock, $large_active, $large_lock, $large_unopen),
            'large_sort_index' => Util::CheckAppVersion('2.5.2') !== '小' ? [0, 2] : array_merge($large_unlocking, $large_unlock, $large_active, $large_lock, $large_unopen), // 合盘报告上线 固定第一个
            'small_sort_index' => array_merge($small_unlocking, $small_unlock, $small_active, $small_lock, $small_unopen),
            'bar_sort_index' => $bar_sort_index
        ];
        return show(config('code.success'), '一生报告', $data);
    }

    /**
     * 本命报告详情
     * @throws Exception
     */
    public function detail()
    {
        $gid = input('gid/d', 0);
        if (!in_array($gid, [39, 40, 41, 42, 52], true))
        {
            return show(config('code.error'), '未知的商品');
        }
        $rid = input('rid/d', 0);
        if (!$rid && !$this->user['rid'])
        {
            return show(406, '档案缺失，去添加档案');
        }
        $rid = $rid ?: $this->user['rid'];

        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || (int)$recode['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        $uid = $this->user['id'];
        $NatalReportModel = new \app\common\cachemodel\NatalReport();

        if (!$gid)
        {
            return show(config('code.error'), '请求异常');
        }

        //获取商品类型
        $goodData = (new NatalGoods())->getGoods();
        // 判断当前解锁状态
        // $unlockReport = $NatalReportModel->getNatalReport($uid, $rid);
        $unlockReport = $NatalReportModel->getNatalReport2($recode);

        if ($unlockReport && isset($unlockReport[$gid]) && (int)$unlockReport[$gid]['status'] === 2)
        {   // 解锁成功
            $gname = '';
            foreach ($goodData as $key => $item)
            {
                if ((int)$item['id'] === $gid)
                {
                    $gname = $item['name'];
                    break;
                }
            }
            $result = [
                'status' => 2,
                'url' => Env::get('host.domain') . '/web/natal_report/index?gid=' . $gid . '&rid=' . $rid,
                'gname' => $gname
            ];
        } else
        {   // 未解锁 或 解锁中
            $orderModel = new \app\common\cachemodel\Orders();
            $status = isset($unlockReport[$gid]) ? ((int)$unlockReport[$gid]['status'] === 2 ? 2 : 1) : 0;
            $unlockingData = [];
            $activeData = [];
            $lockData = [];
            $unlockData = [];
            $gname = '';
            $textNum = 0;
            $unlockNum = 0;
            $headerBg = '';
            $contentBg = '';
            $natalReportPrice = [];
            $activingModel = new ZhunleActivity();
            // 获取合盘报告商品
            if (Util::getSynastryReportSwitch() && Util::CheckAppVersion('2.5.2') !== '小')
            {
                $synastryReportGoods = (new \app\common\cachemodel\Goods())->GoodsTypeInfo(17);
                $goodData = array_merge($synastryReportGoods, $goodData);
            }
            //获取报告商品图片
            $reportImage = ConfigManage::natalReportGoodImage(1);
            foreach ($goodData as $key => $item)
            {
                $item['id'] = isset($item['id']) ? (int)$item['id'] : 0;
                $discount_price = null;
                $timeRange = null;
                $goodType = (isset($item['good_type']) && $item['good_type'] === 17) ? 17 : 7;

                $unlockNumber = $orderModel->getTotalPrepaidOrder($goodType, $item['id']);
                // 获取活动商品信息
                $activing = $activingModel->getActivingGood($goodType, $item['id']);
                if ($activing)
                {
                    $actiGids = explode(',', $activing['gids']);
                    if (in_array($item['id'], $actiGids, false))
                    {
                        $discount_price = sprintf('%.2f', $item['now_prize'] * $activing['attr']);
                    }
                    $timeRange = $activing['end_time'] - time();
                }

                if ($item['id'] === $gid)
                {
                    $natalReportPrice = [
                        'now_price' => $discount_price ?? $item['now_prize'],
                        'active_time' => $timeRange ?? 0,
                    ];
                    $gname = $item['name'];
                    $unlockNum = $item['base_num'] + $unlockNumber;
                    $textNum = $item['text_num'];
                    $headerBg = $item['header_bg'];
                    $contentBg = $item['content_bg'];
                } else
                {
                    if ((int)$item['status'] !== 2)
                    {
                        if ($goodType === 17)
                        {
                            // 检测 是否购买过
                            $unlockStatus = (new ZlSynastryReport())->getUserHasReportUnlockStatus($uid, $rid, 0, $item['srid']);
                            $unlock_status = $unlockStatus ? 2 : 0;
                        } else
                        {
                            if (isset($unlockReport[$item['id']]))
                            {
                                if ((int)$unlockReport[$item['id']]['status'] === 2)
                                {
                                    $unlock_status = 2;//已解锁
                                } else
                                {
                                    $unlock_status = 1;//计算中
                                }
                            } else
                            {
                                $unlock_status = 0;//未解锁
                            }
                        }
                    } else
                    {
                        $unlock_status = 3;//未开放
                    }
                    if ($goodType === 17)
                    {
                        $d = [
                            'gid' => $item['id'],
                            'status' => $unlock_status,
                            'bg_img' => $item['bg_img'] ?? '',
                            'gcolor' => $item['color'] ?? '',
                            'gname' => $item['name'] ?? '',
                            'unlock_num' => $item['base_num'] + $unlockNumber,
                            'active_time' => $timeRange ?? 0,
                            'target' => 'local',
                            'link' => $unlock_status === 0 ?
                                "synastry_report_detail?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=1" :    // 下单介绍页
                                "synastry_report_list?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=1"  // 查看合盘报告列表
                        ];
                    } else
                    {
                        $d = [
                            'gid' => $item['id'],
                            'status' => $unlock_status,
                            'bg_img' => $reportImage['large'][$item['flag']] ?? '',
                            'gcolor' => $item['color'] ?? '',
                            'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
                            'unlock_num' => $item['base_num'] + $unlockNumber,
                            'active_time' => $timeRange ?? 0,
                            'target' => 'local',
                            'link' => "report_details?rid={$rid}&gid={$item['id']}&need_auth=1"
                        ];
                    }

                    if ($d['status'] === 1)
                    {   // 解锁中
                        $unlockingData[] = $d;
                    } elseif ($d['status'] === 0)
                    {   // 未解锁
                        $lockData[] = $d;
                    } elseif ($d['status'] === 2)
                    {   // 已解锁
                        $unlockData[] = $d;
                    }
                }
            }

            $result = [
                'gname' => $gname,
                'status' => $status,
                'text_num' => (int)$textNum,
                'unlock_num' => (int)$unlockNum,
                'header_bg' => $headerBg,
                'content_bg' => $contentBg,
                'natal_report_list' => array_merge($activeData, $unlockData, $unlockingData, $lockData),
                'natal_report_price' => $natalReportPrice
            ];
        }

        return show(config('code.success'), '请求成功', $result);
    }
}
